package person.tanjinfu.jaegerexample;

import io.opentracing.Span;
import io.opentracing.contrib.web.servlet.filter.SpanWrapper;
import io.opentracing.contrib.web.servlet.filter.TracingFilter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Optional;

public class SpanUtil {
    public static Optional<Span> getActiveSpan() {
        return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
                .filter(requestAttributes -> ServletRequestAttributes.class.isAssignableFrom(requestAttributes.getClass()))
                .map(requestAttributes -> ((ServletRequestAttributes) requestAttributes))
                .map(ServletRequestAttributes::getRequest)
                .map(httpServletRequest -> httpServletRequest.getAttribute(TracingFilter.SERVER_SPAN_WRAPPER))
                .map(object -> ((SpanWrapper) object))
                .map(SpanWrapper::get);
    }


}
